package com.sk.cardeal.utils;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.sk.cardeal.app.MyApplication;
import com.tencent.tinker.anno.DefaultLifeCycle;
import com.tencent.tinker.lib.tinker.TinkerInstaller;
import com.tencent.tinker.loader.app.ApplicationLike;
import com.tencent.tinker.loader.app.DefaultApplicationLike;
import com.tencent.tinker.loader.shareutil.ShareConstants;

import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by sunke on 2018/2/28.
 */

@DefaultLifeCycle(application = ".SimpleTinkerInApplication",
        flags = ShareConstants.TINKER_ENABLE_ALL,
        loadVerifyFlag = false)
public class MyApplicationLike extends DefaultApplicationLike {


    private static Application sInstance;
    private static MyApplicationLike applicationLike;
    private ArrayList<AppCompatActivity> activityList;
    private String cookie;
    public int wxPay = 0;
    private static OSSClient oss;
    private static boolean hasGotToken = false;

    public static boolean isHasGotToken() {
        return hasGotToken;
    }

    public  int getWxPay() {
        return wxPay;
    }

    public  void setWxPay(int wxPay) {
        this.wxPay = wxPay;
    }

    public String getCookie() {
        return cookie;
    }

    public  void setCookie(String cookie) {
        this.cookie = cookie;
    }

    public static ApplicationLike getApplicationLike() {
        return applicationLike;
    }

    public MyApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }


    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        TinkerInstaller.install(this);

        applicationLike = this;

        sInstance = getApplication();

        x.Ext.init(sInstance);

        initAccessTokenWithAkSk();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

//        CrashHandler crashHandler = CrashHandler.getInstance();
//        crashHandler.init(getApplicationContext());

        activityList = new ArrayList<>();
        getAppInfo();

        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(sInstance);            // 初始化 JPush

        /****************oss初始化配置**************/
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(HttpAddress.accessKeyId, HttpAddress.accessKeySecret);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSSLog.enableLog();
        oss = new OSSClient(getApplication(), HttpAddress.endpoint, credentialProvider, conf);
    }

    public static OSSClient getOss() {
        return oss;
    }

    public void setOss(OSSClient oss) {
        this.oss = oss;
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager)getAppContext(). getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getAppContext().getPackageName();
        int myPid = android.os.Process.myPid();

        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public ArrayList<AppCompatActivity> getActivityList() {
        return activityList;
    }

    /**
     * 获取application 单例
     *
     * @return
     */
    public static Application getInstance() {
        return sInstance;
    }

    /**
     * 获取全局的Context
     * 能用全局尽量用全局，防止内存泄漏
     *
     * @return
     */
    public static Context getAppContext() {
        return sInstance.getApplicationContext();
    }

    public void finishApp() {
        for (AppCompatActivity activity : activityList) {
            activity.finish();
        }
    }

    private String getAppInfo() {
        try {
            String pkName = getAppContext().getPackageName();
            String versionName = getAppContext().getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            int versionCode = getAppContext().getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            Log.v("getAppInfo",pkName);
            return pkName ;
        } catch (Exception e) {
        }
        return null;
    }


    private void initAccessTokenWithAkSk() {
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
            }
        }, getAppContext(), "xuysl9VANwTihNK5v16URmhG", "4C5CnlUI6XR1CZcgmVViN55xMKW1yzMG");
    }


}
